﻿using System.IO;
using System.Net;
using System.Text;
using Fizzler.Systems.HtmlAgilityPack;
using HtmlAgilityPack;

namespace HtmlDeploy
{
    public class Script
    {
        private readonly HtmlDocument html;
        private readonly string path;

        public Script(string path)
        {
            html = new HtmlDocument();
            html.Load(path);

            this.path = path.Substring(0, path.LastIndexOf(@"\") + 1);
        }

        public string Process()
        {
            return GetScripts();
        }

        private string GetScripts()
        {
            var scripts = html.DocumentNode.QuerySelectorAll("script");

            var sb = new StringBuilder();

            foreach (var script in scripts)
            {
                if (!string.IsNullOrEmpty(script.InnerText.Trim()) && string.IsNullOrEmpty(script.GetAttributeValue("src", "")))
                    sb.AppendLine(script.InnerText);
                else
                    sb.AppendLine(External(script.GetAttributeValue("src", "")));
            }

            return sb.ToString();
        }

        private string External(string src)
        {
            src = src.ToLower();

            if (src.StartsWith("http"))
                return ExternalWeb(src);

            using (var sr = new StreamReader(path + src))
            {
                return sr.ReadToEnd();
            }
        }


        private string ExternalWeb(string url)
        {
            var webRequest = WebRequest.Create(url);
            var response = (HttpWebResponse)webRequest.GetResponse();

            if (response == null)
                return "";
             
            try
            {
                var stream = response.GetResponseStream();

                if (stream == null)
                    return "";

                var streamReader = new StreamReader(stream, true);

                try
                {
                    return streamReader.ReadToEnd();
                }
                finally
                {
                    streamReader.Close();
                }
            }
            finally
            {
                response.Close();
            }
        }
    }
}
